﻿using AntUnion.FrameWork.Util;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace AntUnion.FrameWork.Web.Areas.Console.Controllers
{
    public class ControllerBase : Controller
    {
        public int expires = 60;

        #region cookie 读写
        /// <summary>
        /// 设置本地cookie
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="value">值</param>  
        /// <param name="minutes">过期时长，单位：分钟</param>      
        protected void SetCookies(string key, string value, int minutes = 0)
        {
            if (minutes > 0)
            {
                HttpContext.Response.Cookies.Append(key, value, new CookieOptions
                {
                    Expires = DateTimeUtil.Now.AddMinutes(minutes)
                });
            }
            else
            {
                HttpContext.Response.Cookies.Append(key, value);
            }
        }
        /// <summary>
        /// 删除指定的cookie
        /// </summary>
        /// <param name="key">键</param>
        protected void DeleteCookies(string key)
        {
            HttpContext.Response.Cookies.Delete(key);
        }

        /// <summary>
        /// 获取cookies
        /// </summary>
        /// <param name="key">键</param>
        /// <returns>返回对应的值</returns>
        protected string GetCookies(string key)
        {
            HttpContext.Request.Cookies.TryGetValue(key, out string value);
            if (string.IsNullOrEmpty(value))
                value = string.Empty;
            return value;
        }
        #endregion

        #region session 读写

        /// <summary>
        /// 设置session
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="value">值</param>    
        protected void SetSessions(string key, object value)
        {
            HttpContext.Session.Set(key, ByteConvertUtil.Serialize(value));
        }

        /// <summary>
        /// 获取session
        /// </summary>
        /// <param name="key">键</param>   
        protected T GetSession<T>(string key)
        {
            HttpContext.Session.TryGetValue(key, out byte[] result);
            if (result != null)
                return (T)ByteConvertUtil.Deserialize<T>(result);
            return default;
        }

        /// <summary>
        /// 删除指定的cookie
        /// </summary>
        /// <param name="key">键</param>
        protected void DeleteSessions(string key)
        {
            HttpContext.Session.Remove(key);
        }

        #endregion

        #region 获取客户端IP

        protected string GetIp()
        {
            return HttpContext.Connection.RemoteIpAddress.ToString();
        }

        #endregion
    }
}